package com.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.model.XiaocaiIpTimesInfo;
import com.model.XiaocaiUrls;
import com.model.XiaocaiUser;
import com.model.XiaocaiWebConfig;
import com.model.XiaocaiWorkInfo;
import com.service.impl.RedisBase;

@Service
public class TaskJob {
	public static Logger log = Logger.getLogger(TaskJob.class);
	@Resource
	private XiaocaiUrlsService xiaocaiUrlsService;
	@Resource
	private RedisBase redisBase;
	@Resource
	private XiaocaiUserService xiaocaiUserService;
	@Resource
	private WebConfigInfoService webConfigInfoService;
	private static XiaocaiWebConfig xiaocaiWebConfig = null;

	public void SayHello() {
		// 取出数据保存到内存数据库redis中
		if (redisBase.LISTS.llen("urls") < 100) {
			List<XiaocaiUrls> listXiaocaiUrls = xiaocaiUrlsService
					.getRandomUrlsByLimit(1000);
			Gson gson = new Gson();
			if (null != listXiaocaiUrls) {
				for (XiaocaiUrls xiaocaiUrls : listXiaocaiUrls) {
					redisBase.LISTS.lpush("urls", gson.toJson(xiaocaiUrls));
				}
			}
		}
	}

	/**
	 * 在每晚12点执行刷新网址已完成数量
	 */
	public void updateDataAtZero() {
		xiaocaiUrlsService.updataFinishedTimeZero();
	}

	/*
	 * 执行 SQL，给刷的会员加分，相应的链接减分 并且用户一分钟之内的点击数清零
	 */
	public void executeSql() {
		try {
			if (null == xiaocaiWebConfig)
				xiaocaiWebConfig = webConfigInfoService.getXiaocaiWebConfig();
			while(redisBase.LISTS.llen("urls_sql")>0){
				Gson gson = new Gson();
					XiaocaiWorkInfo xiaocaiWorkInfo = gson.fromJson(redisBase.LISTS.rpop("urls_sql"),
							XiaocaiWorkInfo.class);
					// 获取刷分人级别
					XiaocaiUser worker = xiaocaiUserService
							.selectByPrimaryKeyByRedis(xiaocaiWorkInfo
									.getUserId());
					// 根据级别获取刷分得到的百分比
					int percent = 50;
					int referPercent = 5;
					// 获取上级ID
					long refer = 1;
					if (null != worker) {
						switch (worker.getUserLevel()) {
						case 0:
							percent = xiaocaiWebConfig
									.getLevel_point_refer_one();
							referPercent = xiaocaiWebConfig
									.getLevel_refer_agent1();
							break;
						case 1:
							percent = xiaocaiWebConfig
									.getLevel_point_refer_two();
							referPercent = xiaocaiWebConfig
									.getLevel_refer_agent2();
							break;
						case 2:
							percent = xiaocaiWebConfig
									.getLevel_point_refer_three();
							referPercent = xiaocaiWebConfig
									.getLevel_refer_agent3();
							break;
						case 3:
							percent = xiaocaiWebConfig
									.getLevel_point_refer_four();
							referPercent = xiaocaiWebConfig
									.getLevel_refer_agent4();
							break;
						default:
							break;
						}
						if (worker.getReferUserId() != 0) {
							refer = worker.getReferUserId();
						}
					}
					// 给刷网址的人加分
					xiaocaiUserService
							.addPoint(xiaocaiWorkInfo.getUserId(),
									((float) (xiaocaiWorkInfo.getPoint())
											* percent / 100));

					// 给上级加分
					float referPoint = ((float) (xiaocaiWorkInfo.getPoint())
							* ((float) percent / 100) * ((float) referPercent / 100));
					xiaocaiUserService.addPoint(refer, referPoint);

					// 给网址减分
					xiaocaiUrlsService.addPoint(xiaocaiWorkInfo.getUrlId(),
							0 - xiaocaiWorkInfo.getPoint(),
							xiaocaiWorkInfo.getFinishedHour());

					// 删除此操作的SQL
					String fieid = "urlId_"
							+ String.valueOf(xiaocaiWorkInfo.getUrlId())
							+ "_userId_"
							+ String.valueOf(xiaocaiWorkInfo.getUserId());
					//redisBase.HASH.hdel("urls_sql", fieid);
			}
			// 查询比例(一分钟之类用户点击链接数/一分钟之类某个用户的刷的IP数)
			if (!redisBase.HASH.hgetall("urls_minute").isEmpty()) {
				Map<String, String> map = redisBase.HASH.hgetall("urls_minute");
				Set<String> key = map.keySet();
				Gson gson = new Gson();
				for (Iterator it = key.iterator(); it.hasNext();) {
					String s = (String) it.next();
					XiaocaiIpTimesInfo xiaocaiIpTimesInfo = gson.fromJson(
							map.get(s), XiaocaiIpTimesInfo.class);
					long clickCount = xiaocaiIpTimesInfo.getClickCount();
					// System.out.println("@@@@@@@@@点击数:" + clickCount);
					long userId = xiaocaiIpTimesInfo.getUserId();
					String keyString = "customer_" + "userId_"
							+ String.valueOf(userId) + "_ip_*";
					int ipCount = redisBase.KEYS.kyes(keyString).size();
					// System.out.println("@@@@@@@@@ip数:" + ipCount);
					// 一个用户的点击/ip比例
					long percent = clickCount / (ipCount == 0 ? 1 : ipCount);
					// System.out.println("@@@@@@@@@点击数/ip数:" + percent);
					if (percent > xiaocaiWebConfig.getWarn_times_for_ip()) {
						// 发出警告一次(一个ip一分钟不能点击超过10次)
						xiaocaiUserService.addWarned(userId, 1);
						/*
						 * System.out.println("发出警告一次(一个ip一分钟不能点击超过10次):用户编号：" +
						 * userId);
						 */
					}
				}
				// 1分钟清理一次点击数
				redisBase.HASH.hdel("urls_minute");
			}
		} catch (Exception e) {
			return;
		}
	}
}
